package org.example.interceptor;

import org.example.threadlocal.UserContext;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class UserInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从请求头或参数中获取用户信息
        String username = "username"; //
        if (username != null) {
            UserContext.setUser(username); // 设置用户信息到上下文
        }
        return true; // 继续执行后续拦截器和控制器
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 请求完成后清理用户信息
        UserContext.clear();
    }
}
